﻿namespace Ngs
{
    using System;
    using System.Linq.Expressions;
    using System.Text;
    using Ngs.Extensions;

    public class ObjectWriter<T>
    {
        private bool init;
        private StringBuilder builder;
        private T item;

        public ObjectWriter(T item)
            : this(item, new StringBuilder())
        {
        }

        public ObjectWriter(T item, StringBuilder builder)
        {
            ExceptionFactory.ThrowIfArgumentNull(item);
            ExceptionFactory.ThrowIfArgumentNull(builder);
            this.item = item;
            this.builder = builder;
        }

        public ObjectWriter<T> WriteMember(Expression<Func<T, string>> memberAccessor)
        {
            ExceptionFactory.ThrowIfArgumentNull(memberAccessor);

            var member = memberAccessor.Body as MemberExpression;

            ExceptionFactory.ThrowInvalidOperation(member == null, "Lambda expression is not a member of the object.");

            if (init)
            {
                builder.WithComma();
            }

            var func = memberAccessor.Compile();
            builder.Append(member.Member.Name).WithColon();
            builder.Append(func(item) ?? string.Empty);

            init = true;
            return this;
        }

        public override string ToString()
        {
            return this.builder.ToString();
        }
    }
}
